using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows;

namespace PluginManagerWPF
{
    public class PluginInfo : INotifyPropertyChanged
    {
        private bool isDownloaded;
        private string toolTip = string.Empty;
        public string Name { get; set; } = string.Empty;
        public string DisplayName { get; set; } = string.Empty;
        public string DownloadUrl { get; set; } = string.Empty;
        public string FileName { get; set; } = string.Empty;
        public string ToolTip
        {
            get => toolTip;
            set
            {
                if (toolTip != value)
                {
                    toolTip = value;
                    OnPropertyChanged(nameof(ToolTip));
                }
            }
        }
        public bool IsDownloaded
        {
            get => isDownloaded;
            set
            {
                if (isDownloaded != value)
                {
                    isDownloaded = value;
                    OnPropertyChanged(nameof(IsDownloaded));
                }
            }
        }
        public bool IsExternalTool { get; set; }
        public bool IsBuiltInDll { get; set; }
        public bool IsZipFile { get; set; }
        public string ExeFileName { get; set; } = string.Empty;
        public string ExtractFolder { get; set; } = string.Empty;

        public string PluginType
        {
            get
            {
                if (IsBuiltInDll) return "类库文件";
                if (IsExternalTool) return "可执行程序";
                if (IsZipFile) return "压缩包文件";
                return "PE文件";
            }
        }

        public event PropertyChangedEventHandler? PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public class PluginManager
    {
        public ObservableCollection<PluginInfo> Plugins { get; } = new ObservableCollection<PluginInfo>();
        public string PluginsDirectory { get; }

        public PluginManager()
        {
            PluginsDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "plugins");

            AppDomain.CurrentDomain.AssemblyResolve += EnhancedAssemblyResolve;

            InitializePluginList();
            InitializePlugins();
        }

        private Assembly? EnhancedAssemblyResolve(object? sender, ResolveEventArgs args)
        {
            return null;
        }

        private void InitializePluginList()
        {
            var pluginList = new List<PluginInfo>
            {
                new PluginInfo
                {
                    Name = "UniversalFileExtractor",
                    DisplayName = "万能二进制提取器",
                    DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/FileExtractor.dll",
                    FileName = "FileExtractor.dll",
                    IsExternalTool = false,
                    IsBuiltInDll = true,
                    ToolTip = "一个支持各种标准计算机文件的二进制提取器"
                },
                new PluginInfo
                {
                    Name = "UniversalByteRemover",
                    DisplayName = "万能字节移除器",
                    DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/ByteRemover.dll",
                    FileName = "ByteRemover.dll",
                    IsExternalTool = false,
                    IsBuiltInDll = true,
                    ToolTip = "一个可以随意删除各种字节的工具，主要用它来删除各种游戏文件里填充的字节，unity游戏里经常有假文件头文件，此工具和万能二进制提取器配合使用效果更佳"
                },
                new PluginInfo
                {
                    Name = "quickbmsbatch",
                    DisplayName = "quickbms批量提取器",
                    DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/quickbmsbatch.dll",
                    FileName = "quickbmsbatch.dll",
                    IsExternalTool = false,
                    IsBuiltInDll = true,
                    ToolTip = "quickbms辅助工具，上手简单，帮助不会使用命令行的小伙伴来批量执行解包操作"
                },
                new PluginInfo
                {
                    Name = "FavoritesManager",
                    DisplayName = "收藏夹管理器",
                    DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/FavoritesManager.dll",
                    FileName = "FavoritesManager.dll",
                    IsExternalTool = false,
                    IsBuiltInDll = true,
                    ToolTip = "一个存储各种资源网站的链接收藏夹，取代传统浏览器的收藏夹，防止用户忘记浏览器的账号密码，除非网站被关闭，否则这个收藏夹管理器可以用到老"
                },
                new PluginInfo
                {
                    Name = "SuperToolbox",
                    DisplayName = "超级工具箱",
                    DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/Super-toolbox.dll",
                    FileName = "Super-toolbox.dll",
                    IsExternalTool = false,
                    IsBuiltInDll = true,
                    ToolTip = "我制作的解包工具，可打包、解包、转换、压缩和解压，目前已经添加了100多个工具，主要用来解包游戏，查看使用手册帮助你了解各个工具的用途"
                },
                new PluginInfo
                {
                    Name = "Sofdec2Viewer",
                    DisplayName = "USM视频查看器汉化版",
                    DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/Sofdec2_Viewer.exe",
                    FileName = "Sofdec2_Viewer.exe",
                    IsExternalTool = true,
                    IsBuiltInDll = false,
                    ToolTip = "使用它可以直接预览查看CRIWARE的未加密的usm视频"
                },
                new PluginInfo
                {
                    Name = "RadVideo",
                    DisplayName = "bink视频播放器",
                    DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/radvideo64.exe",
                    FileName = "radvideo64.exe",
                    IsExternalTool = true,
                    IsBuiltInDll = false,
                    ToolTip = "使用它可以直接预览查看rad game tools的bink视频，这些视频的文件扩展名一般为bk2格式，但是地雷社有些游戏经常将其伪装成usm视频"
                },
                new PluginInfo
                {
                    Name = "QuickBMS",
                    DisplayName = "quickbms汉化版",
                    DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/quickbms.exe",
                    FileName = "quickbms.exe",
                    IsExternalTool = true,
                    IsBuiltInDll = false,
                    ToolTip = "我已经汉化了命令行窗口里的部分文本"
                },
                new PluginInfo
                {
                    Name = "quickbms_4gb_files",
                    DisplayName = "quickbms_4gb_files汉化版",
                    DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/quickbms_4gb_files.exe",
                    FileName = "quickbms_4gb_files.exe",
                    IsExternalTool = true,
                    IsBuiltInDll = false,
                    ToolTip = "我已经汉化了命令行窗口里的部分文本，4gb版本"
                },
                new PluginInfo
                {
                    Name = "RioX",
                    DisplayName = "RioX汉化版",
                    DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/RioX.exe",
                    FileName = "RioX汉化版.exe",
                    IsExternalTool = true,
                    IsBuiltInDll = false,
                    ToolTip = "一个可以从galgame游戏rio文件里面提取图片的工具",
                },
                new PluginInfo
                {
                    Name = "PakExplorer",
                    DisplayName = "LUCA system pak解包器汉化版",
                    DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/pak_explorer.exe",
                    FileName = "pak_explorer.exe",
                    IsExternalTool = true,
                    IsBuiltInDll = false,
                    ToolTip = "一个可以解包LUCA system pak的工具"
                },
                new PluginInfo
                {
                    Name = "PSound",
                    DisplayName = "PlayStation音频提取器",
                    DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/PSound.exe",
                    FileName = "PSound.exe",
                    IsExternalTool = true,
                    IsBuiltInDll = false,
                    ToolTip = "一个可以从PlayStation游戏文件里面提取pcm、vag、at3等音频的工具"
                },
                new PluginInfo
                {
                    Name = "WinAsar",
                    DisplayName = "WinAsar汉化版",
                    DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/WinAsar.exe",
                    FileName = "WinAsar汉化版.exe",
                    IsExternalTool = true,
                    IsBuiltInDll = false,
                    ToolTip = "一个可以解包和打包asar的工具"
                },
                new PluginInfo
                {
                    Name = "AudioCUE",
                    DisplayName = "AudioCUE编辑器",
                    DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/ACE.exe",
                    FileName = "ACE.exe",
                    IsExternalTool = true,
                    IsBuiltInDll = false,
                    ToolTip = "一个可以编辑acb/awb的工具，同时它还是个播放器，可以acb/awb里面的hca，并且可以把hca转换成adx、dsp、wav"
                },
                new PluginInfo
                {
                    Name = "WinPCK",
                    DisplayName = "完美世界pck解包工具",
                    DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/WinPCK.exe",
                    FileName = "WinPCK.exe",
                    IsExternalTool = true,
                    IsBuiltInDll = false,
                    ToolTip = "一个支持很多完美世界游戏的pck解包工具"
                },
                new PluginInfo
                {
                    Name = "RetsukoSoundTool",
                    DisplayName = "3DS/Wiiu音频提取器",
                    DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/RetsukoSoundTool.exe",
                    FileName = "RetsukoSoundTool.exe",
                    IsExternalTool = true,
                    IsBuiltInDll = false,
                    ToolTip = "一个支持任天堂3ds游戏和wiiu游戏的音频提取器"
                },
                new PluginInfo
                {
                    Name = "Motrix",
                    DisplayName = "免费不限速下载器",
                    DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/Motrix_x64.exe",
                    FileName = "Motrix_x64.exe",
                    IsExternalTool = true,
                    IsBuiltInDll = false,
                    ToolTip = "一个免费的下载器，没开迅雷会员的可以试试"
                },
                new PluginInfo
                {
                    Name = "UmodelHelper",
                    DisplayName = "Umodel辅助器",
                    DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/UmodelHelper.exe",
                    FileName = "UmodelHelper.exe",
                    IsExternalTool = true,
                    IsBuiltInDll = false,
                    ToolTip = "Umodel的辅助工具，使用C#语言编写，帮助用户在解包虚幻引擎游戏的时候不用频繁输入密钥，只要在这个工具里面添加游戏密钥就可以用它启动umodel了"
                },
                new PluginInfo
                {
                    Name = "cmake-gui",
                    DisplayName = "cmakegui汉化版",
                    DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/cmake-gui.exe",
                    FileName = "cmake-gui.exe",
                    IsExternalTool = true,
                    IsBuiltInDll = false,
                    ToolTip = "我汉化的CMakegui，主窗口大部分文本已汉化，帮助用户把CMake的CMakelist.txt生成其他编译器需要的方案解决文件"
                },
                new PluginInfo
                {
                    Name = "QuickWaveBank",
                    DisplayName = "xwb打包解包工具",
                    DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/QuickWaveBank.exe",
                    FileName = "QuickWaveBank.exe",
                    IsExternalTool = true,
                    IsBuiltInDll = false,
                    ToolTip = "一个可以打包解包xwb文件的工具"
                },
                new PluginInfo
                {
                    Name = "CpkFileBuilder",
                    DisplayName = "CPK官方打包解包工具",
                    DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/CpkFileBuilder.zip",
                    FileName = "CpkFileBuilder.zip",
                    IsExternalTool = true,
                    IsBuiltInDll = false,
                    IsZipFile = true,
                    ExeFileName = "CpkFileBuilder.exe",
                    ExtractFolder = "CpkFileBuilder",
                    ToolTip = "Criware的CPK官方打包解包工具，已被我汉化大部分文本"
                },
                new PluginInfo
                {
                    Name = "IDM",
                    DisplayName = "IDM下载器",
                    DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/IDM.zip",
                    FileName = "IDM.zip",
                    IsExternalTool = true,
                    IsBuiltInDll = false,
                    IsZipFile = true,
                    ExeFileName = "IDMan.exe",
                    ExtractFolder = "IDM",
                    ToolTip = "一个免费的下载器，和Motrix差不多"
                },
                new PluginInfo
                {
                    Name = "PVRViewer",
                    DisplayName = "世嘉游戏PVR查看器",
                    DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/PVRViewer.zip",
                    FileName = "PVRViewer.zip",
                    IsExternalTool = true,
                    IsBuiltInDll = false,
                    IsZipFile = true,
                    ExeFileName = "PVRViewer.exe",
                    ExtractFolder = "PVRViewer",
                    ToolTip = "PVRTC查看器和解包工具，此PVR非彼PVR，使用TexturePackerGui无效"
                },
                new PluginInfo
                {
                    Name = "GD-ROM-Explorer",
                    DisplayName = "世嘉游戏rom解包器",
                    DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/GD-ROM-Explorer.zip",
                    FileName = "GD-ROM-Explorer.zip",
                    IsExternalTool = true,
                    IsBuiltInDll = false,
                    IsZipFile = true,
                    ExeFileName = "GD-ROM Explorer.exe",
                    ExtractFolder = "GD-ROM-Explorer",
                    ToolTip = "世嘉游戏cdi、gdi格式的rom解包器"
                },
                new PluginInfo
                {
                    Name = "CDmage",
                    DisplayName = "光盘rom解包器",
                    DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/CDmage.zip",
                    FileName = "CDmage.zip",
                    IsExternalTool = true,
                    IsBuiltInDll = false,
                    IsZipFile = true,
                    ExeFileName = "CDmage.exe",
                    ExtractFolder = "CDmage",
                    ToolTip = "一个可以解包很多ISO游戏镜像的工具，如果你在解包ISO镜像时遇到了困难，可以试试它"
                },
                new PluginInfo
                {
                    Name = "VGMTrans",
                    DisplayName = "VGMTrans音频提取器",
                    DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/VGMTrans.zip",
                    FileName = "VGMTrans.zip",
                    IsExternalTool = true,
                    IsBuiltInDll = false,
                    IsZipFile = true,
                    ExeFileName = "VGMTrans.exe",
                    ExtractFolder = "VGMTrans",
                    ToolTip = "一个可以从任天堂nds游戏里面提取音频的工具，比如mid格式"
                },
                new PluginInfo
                {
                    Name = "CitricComposer",
                    DisplayName = "柠檬音乐工坊",
                    DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/CitricComposer.zip",
                    FileName = "CitricComposer.zip",
                    IsExternalTool = true,
                    IsBuiltInDll = false,
                    IsZipFile = true,
                    ExeFileName = "Citric Composer.exe",
                    ExtractFolder = "CitricComposer",
                    ToolTip = "一个支持任天堂3ds、wiiu游戏的音频播放器和解包器，不支持wii，该软件已被我使用源码汉化，还修复了一个运行报错的bug，编译报错不可怕，可怕的是运行报错"
                },
                new PluginInfo
                {
                    Name = "toolbox",
                    DisplayName = "任天堂toolbox",
                    DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/toolbox.zip",
                    FileName = "toolbox.zip",
                    IsExternalTool = true,
                    IsBuiltInDll = false,
                    IsZipFile = true,
                    ExeFileName = "toolbox.exe",
                    ExtractFolder = "toolbox",
                    ToolTip = "一个支持任天堂3ds、wiiu游戏的解包工具箱，似乎不是很好用"
                },
                new PluginInfo
                {
                    Name = "CPKBrowser.exe",
                    DisplayName = "CPK浏览器",
                    DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/CPKBrowser.exe",
                    FileName = "CPKBrowser.exe",
                    IsExternalTool = true,
                    IsBuiltInDll = false,
                    ToolTip = "一个CPK解包工具，可以查看cpk文件里面的目录结构，和garbro差不多"
                },
                new PluginInfo
                {
                    Name = "Nartools.exe",
                    DisplayName = "CSOL-Nar解包器",
                    DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/Nartools.exe",
                    FileName = "Nartools.exe",
                    IsExternalTool = true,
                    IsBuiltInDll = false,
                    ToolTip = "CSOL的nar解包工具"
                },
                new PluginInfo
                {
                    Name = "FSBank",
                    DisplayName = "FSB打包工具",
                    DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/fsbank.zip",
                    FileName = "fsbank.zip",
                    IsExternalTool = true,
                    IsBuiltInDll = false,
                    IsZipFile = true,
                    ExeFileName = "fsbank.exe",
                    ExtractFolder = "fsbank",
                    ToolTip = "Fmod的fsb样本打包器，主窗口大部分文本已被我汉化，想打包fsb的可以试试"
                }
            };

            foreach (var plugin in pluginList)
            {
                Plugins.Add(plugin);
            }
        }

        public void InitializePlugins()
        {
            if (!Directory.Exists(PluginsDirectory))
            {
                Directory.CreateDirectory(PluginsDirectory);
            }

            foreach (var plugin in Plugins)
            {
                string filePath;
                if (plugin.IsZipFile && !string.IsNullOrEmpty(plugin.ExtractFolder))
                {
                    filePath = Path.Combine(PluginsDirectory, plugin.ExtractFolder, plugin.ExeFileName);
                }
                else
                {
                    filePath = Path.Combine(PluginsDirectory, plugin.FileName);
                }
                plugin.IsDownloaded = File.Exists(filePath);
            }
        }

        public void LaunchPlugin(PluginInfo plugin)
        {
            if (IsDependencyFile(plugin))
            {
                MessageBox.Show($"{plugin.DisplayName} 是依赖文件，无法直接启动。", "提示",
                    MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            if (!plugin.IsDownloaded)
            {
                MessageBox.Show($"请先下载{plugin.DisplayName}", "提示",
                    MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            try
            {
                string filePath;
                string workingDirectory = PluginsDirectory;

                if (plugin.IsZipFile)
                {
                    filePath = Path.Combine(PluginsDirectory, plugin.ExtractFolder, plugin.ExeFileName);
                    workingDirectory = Path.Combine(PluginsDirectory, plugin.ExtractFolder);
                }
                else
                {
                    filePath = Path.Combine(PluginsDirectory, plugin.FileName);
                }

                if (!File.Exists(filePath))
                {
                    plugin.IsDownloaded = false;
                    MessageBox.Show($"{plugin.DisplayName}文件不存在，请重新下载", "错误",
                        MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                if (plugin.IsExternalTool || plugin.IsZipFile)
                {
                    Process.Start(new ProcessStartInfo
                    {
                        FileName = filePath,
                        UseShellExecute = true,
                        WorkingDirectory = workingDirectory
                    });
                }
                else if (plugin.IsBuiltInDll)
                {
                    LaunchBuiltInDll(plugin, filePath);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"启动{plugin.DisplayName}失败:{ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private bool IsDependencyFile(PluginInfo plugin)
        {
            return false;
        }

        private void LaunchBuiltInDll(PluginInfo plugin, string filePath)
        {
            try
            {
                if (plugin.FileName.Equals("Super-toolbox.dll", StringComparison.OrdinalIgnoreCase))
                {
                    LaunchSuperToolboxSafely(plugin, filePath);
                }
                else
                {
                    LaunchBuiltInDllNormal(plugin, filePath);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载{plugin.DisplayName}失败:{ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void LaunchSuperToolboxSafely(PluginInfo plugin, string filePath)
        {
            try
            {
                Assembly assembly = Assembly.LoadFrom(filePath);

                Type? superToolboxType = assembly.GetType("super_toolbox.SuperToolbox");
                if (superToolboxType != null)
                {
                    if (typeof(System.Windows.Forms.Form).IsAssignableFrom(superToolboxType))
                    {
                        LaunchWinFormsForm(plugin, new List<Type> { superToolboxType });
                        return;
                    }
                }

                var formTypes = assembly.GetTypes()
                    .Where(t => t != null && typeof(System.Windows.Forms.Form).IsAssignableFrom(t) && !t.IsAbstract)
                    .ToList();

                if (formTypes.Count > 0)
                {
                    Type? mainFormType = formTypes.FirstOrDefault(t =>
                        (t.Name.Contains("SuperToolbox", StringComparison.OrdinalIgnoreCase) ||
                         t.Name.Contains("Main", StringComparison.OrdinalIgnoreCase))) ?? formTypes[0];

                    if (mainFormType != null)
                    {
                        LaunchWinFormsForm(plugin, new List<Type> { mainFormType });
                        return;
                    }
                }

                throw new Exception("在SuperToolbox中找不到可用的窗体类型");
            }
            catch (ReflectionTypeLoadException)
            {
                RetryLaunchSuperToolbox(plugin, filePath);
            }
        }

        private void LaunchBuiltInDllNormal(PluginInfo plugin, string filePath)
        {
            Assembly assembly = Assembly.LoadFrom(filePath);

            var windowTypes = assembly.GetTypes()
                .Where(t => t != null && typeof(System.Windows.Window).IsAssignableFrom(t) && !t.IsAbstract)
                .ToList();

            var formTypes = assembly.GetTypes()
                .Where(t => t != null && typeof(System.Windows.Forms.Form).IsAssignableFrom(t) && !t.IsAbstract)
                .ToList();

            if (windowTypes.Count == 0 && formTypes.Count == 0)
            {
                throw new Exception($"在{plugin.FileName}中找不到窗体类(WPF Window或WinForms Form)");
            }

            if (windowTypes.Count > 0)
            {
                LaunchWpfWindow(plugin, windowTypes);
            }
            else
            {
                LaunchWinFormsForm(plugin, formTypes);
            }
        }

        private void RetryLaunchSuperToolbox(PluginInfo plugin, string filePath)
        {
            try
            {
                Assembly assembly = Assembly.LoadFrom(filePath);

                Type? superToolboxType = assembly.GetType("super_toolbox.SuperToolbox");
                if (superToolboxType != null)
                {
                    var instance = Activator.CreateInstance(superToolboxType);
                    if (instance is System.Windows.Forms.Form form)
                    {
                        form.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
                        form.Show();
                        return;
                    }
                }

                throw new Exception("无法创建SuperToolbox实例");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"启动SuperToolbox失败:{ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void LaunchWpfWindow(PluginInfo plugin, List<Type> windowTypes)
        {
            Type? mainWindowType = windowTypes.FirstOrDefault(t =>
                t != null && t.Name.Contains("Main", StringComparison.OrdinalIgnoreCase)) ?? windowTypes[0];

            if (mainWindowType == null)
            {
                throw new Exception("无法确定主窗口类型");
            }

            System.Windows.Application.Current.Dispatcher.Invoke(() =>
            {
                var existingWindow = System.Windows.Application.Current.Windows.Cast<System.Windows.Window>()
                    .FirstOrDefault(w => w.GetType() == mainWindowType);

                if (existingWindow != null)
                {
                    if (existingWindow.WindowState == System.Windows.WindowState.Minimized)
                    {
                        existingWindow.WindowState = System.Windows.WindowState.Normal;
                    }
                    existingWindow.Activate();
                    existingWindow.Focus();
                    return;
                }

                System.Windows.Window? mainWindow = Activator.CreateInstance(mainWindowType) as System.Windows.Window;
                if (mainWindow != null)
                {
                    mainWindow.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
                    mainWindow.Show();
                }
                else
                {
                    throw new Exception($"无法创建窗口实例:{mainWindowType.FullName}");
                }
            });
        }

        private void LaunchWinFormsForm(PluginInfo plugin, List<Type> formTypes)
        {
            Type? mainFormType = formTypes.FirstOrDefault(t =>
                t != null && t.Name.Contains("Main", StringComparison.OrdinalIgnoreCase)) ?? formTypes[0];

            if (mainFormType == null) return;

            var existingInstance = System.Windows.Forms.Application.OpenForms.Cast<System.Windows.Forms.Form>()
                .FirstOrDefault(form => form.GetType() == mainFormType);

            if (existingInstance != null)
            {
                if (existingInstance.WindowState == System.Windows.Forms.FormWindowState.Minimized)
                    existingInstance.WindowState = System.Windows.Forms.FormWindowState.Normal;
                existingInstance.BringToFront();
                return;
            }

            if (Activator.CreateInstance(mainFormType) is System.Windows.Forms.Form mainForm)
            {
                mainForm.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
                mainForm.Show();
            }
        }

        public void UninstallPlugin(PluginInfo plugin)
        {
            try
            {
                string filePath = Path.Combine(PluginsDirectory, plugin.FileName);

                if (File.Exists(filePath))
                {
                    if (plugin.IsBuiltInDll && IsDllLoaded(plugin.FileName))
                    {
                        throw new Exception($"{plugin.DisplayName}正在使用中,请重启插件管理器后再尝试卸载。");
                    }
                    File.Delete(filePath);
                }

                if (plugin.IsZipFile && !string.IsNullOrEmpty(plugin.ExtractFolder))
                {
                    string extractFolderPath = Path.Combine(PluginsDirectory, plugin.ExtractFolder);
                    if (Directory.Exists(extractFolderPath))
                    {
                        Directory.Delete(extractFolderPath, true);
                    }
                }

                plugin.IsDownloaded = false;
            }
            catch (Exception ex)
            {
                throw new Exception($"卸载{plugin.DisplayName}失败:{ex.Message}", ex);
            }
        }

        private bool IsDllLoaded(string fileName)
        {
            try
            {
                var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
                string targetPath = Path.Combine(PluginsDirectory, fileName);

                return loadedAssemblies.Any(asm =>
                    !asm.IsDynamic &&
                    !string.IsNullOrEmpty(asm.Location) &&
                    asm.Location.Equals(targetPath, StringComparison.OrdinalIgnoreCase));
            }
            catch
            {
                return false;
            }
        }
    }
}